// pages/user/memberRegister/index.js

import requestUtil from '../../../baseRequest.js'
import requestUrls from '../../../requestUrl.js'
import imageUtils from '../../../utils/imageUtils.js'
import commentUtils from '../../../utils/util.js'
import { $Message } from '../../../components/base/index'

let openid = wx.getStorageSync('openid')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    gender: 'male',
    ifPlateNumber: false,
    authType: '',
    industryId: '',
    showLoading: false,
    // industryList: [],
    hasCar: '',
    idCards:[],
    telPhone:wx.getStorageInfoSync('telPhone'),
    ifUploadId:false,
    ifUploadDriverLicense:false,
    ifUpLoadVincle:false,
  },
  toRegionChange(e){
    const regionNameList = [...e.detail.value, "", "", ""];
    this.setData({
      provinceCity:regionNameList[0]+regionNameList[1]+regionNameList[2],
      provinceName:regionNameList[0],
      cityName:regionNameList[1],
      countyName:regionNameList[2],
    })
  },
  handleChangeSex(event) {
    this.setData({
      gender: event.currentTarget.dataset.gender,
    });
  },
  handleChangeBloodType(event) {
    this.setData({
      bloodType: event.currentTarget.dataset.bloodtype,
    });
  },
  changeHasCar(event) {
    this.setData({
      hasCar: event.currentTarget.dataset.hascar,
    });
  },
  confirmPay() {
    //1.新建用户
    let submitUrl = requestUrls.driver.registerWithCard;
    requestUtil.postRequest(submitUrl, this.data.registerInfo, (res) => {
      if (res.isFail) {
        wx.showModal({
          title: '操作失败',
          content: '提交资料失败：'+res.msg,
          showCancel: false,
          success: res => {
            this.setData({
              showLoading: false
            });
          }
        })
        return
      }
      //2.发起微信支付
      wx.requestPayment({
        timeStamp: res.timestamp,
        nonceStr: res.nonce_str,
        package: res.package,
        signType: 'MD5',
        paySign: res.pay_sign,
        success: (res) => {
          this.handelSuccessPayment()
        },
        fail: function () {
          wx.showModal({
            title: '温馨提醒',
            content: '支付未成功！请重新发起支付',
            showCancel: false,
            confirmText: '确认关闭'
          })
        },
      })
    });
  },
  handelSuccessPayment() {
    const callBackData = {
      openid:wx.getStorageSync('openid')
    }
    let callBackUrl = requestUrls.driver.wxPayCallBack;
    requestUtil.postRequest(callBackUrl, callBackData, (res) => {
      getApp().updateGlobalUserRegisterStatus(true);
      getApp().updateGlobalUserDriverStatus(2);
      wx.showModal({
        title: '温馨提示',
        content: '注册成功',
        showCancel: false,
        success: res => {
          if (res.confirm) {
            wx.redirectTo({
              url: '/pages/user/detailDriver/index',
            })
            this.setData({
              showLoading: false
            });
          }
        }
      })
      })
  },
  submitRegister(event) {

    const { value } = event.detail;
    if (this.checkFormData(value)) {
      this.setData({showLoading:true});
      const { plateNumber, bloodType, authType, gender, mainDriverLicense, vehicleLicense, industryList, industryId, distributeCode, hasCar,idCards,telPhone } = this.data;
      // let driverLience = {}, drivingLience = {},idCardList=[];
      // if(mainDriverLicense){
      //   mainDriverLicense.forEach(item => {
      //     driverLience = { url: item.imageUrl, id: '' };
      //   });
      // }
      // if(vehicleLicense){
      //   vehicleLicense.forEach(item => {
      //     drivingLience = { url: item.imageUrl, id: '' };
      //   });
      // }
      // idCards.forEach(item=>{
      //   idCardList.push({url: item.imageUrl, id: ''});
      // })

      let memberInfo = {
        ...value,
        openid: wx.getStorageSync('openid'),
        hasCar,
        carNumber: plateNumber,
        gender,
        bloodType,
        authType,
        // driverLience,
        // drivingLience,
        // industryIds: [industryList[industryId].id],
        telPhone:telPhone || wx.getStorageSync('telPhone'),
        distributeCode: distributeCode,
        provinceName:this.data.provinceName,
        cityName:this.data.cityName,
        countyName:this.data.countyName,
        address:this.data.provinceCity+value.detailAddress,
        // idCards:idCardList,
      }
      //封装提交内容，跳转支付
      this.setData({
        registerInfo:memberInfo
      })
      this.confirmPay();

      //原始不支付版本逻辑 开始
      // let submitUrl = requestUrls.driver.registerDriver
      // if (this.data.type == '2') {
      //   submitUrl = requestUrls.driver.updateDriverInfo
      // }
      // requestUtil.postRequest(submitUrl, memberInfo, (res) => {
      //   if (res.isFail) {
      //     wx.showModal({
      //       title: '认证失败',
      //       content: res.msg,
      //       showCancel: false,
      //       success: res => {
      //         this.setData({showLoading:false});
      //       }
      //     })
      //     return
      //   }
      //   getApp().updateGlobalUserRegisterStatus(true);
      //   getApp().updateGlobalUserDriverStatus(2);
      //     wx.showModal({
      //       title: '温馨提示',
      //       content: '注册成功',
      //       showCancel: false,
      //       success: res => {
      //         if (res.confirm) {
      //           wx.switchTab({
      //             url: '/pages/user/personal/index',
      //           })
      //           this.setData({showLoading:false});
      //         }
      //       }
      //     })
      // });
      //原始不支付版本逻辑 结束
    }
  },
  checkFormData(data) {
    if (!data.employeeName || data.employeeName == '') {
      this.showErrorMessage('真实姓名不能为空')
      return false
    }
    if(data.employeeName.indexOf(" ")>-1){
      this.showErrorMessage('真实姓名不能含有空格')
      return false
    }
    if(commentUtils.isEmoji(data.employeeName)){
      this.showErrorMessage('真实姓名不能含有表情字符')
      return false
    }
    
    // if (!data.phone || !commentUtils.checkTelphoneNumber(data.phone)) {
    //   this.showErrorMessage('联系方式不符合要求')
    //   return false
    // }
    if (!data.emergencyName) {
      this.showErrorMessage('紧急联系人不能为空')
      return false
    }
    if(data.emergencyName.indexOf(" ")>-1){
      this.showErrorMessage('紧急联系人姓名不能含有空格')
      return false
    }
    if(commentUtils.isEmoji(data.emergencyName)){
      this.showErrorMessage('紧急联系人不能含有表情字符')
      return false
    }
    if (!data.emergencyPhone || !commentUtils.checkTelphoneNumber(data.emergencyPhone)) {
      this.showErrorMessage('紧急联系方式不符合要求')
      return false
    }

    const {  bloodType, gender, authType, mainDriverLicense, vehicleLicense, hasCar ,idCards} = this.data;
    // if (hasCar === 'Y' && !plateNumber) {
    //   this.showErrorMessage('车牌号不能为空')
    //   return false
    // }
    // if (!bloodType) {
    //   this.showErrorMessage('请选择血型')
    //   return false
    // }
    if (!gender) {
      this.showErrorMessage('请选择性别')
      return false
    }
    if (!hasCar) {
      this.showErrorMessage('请选择是否车主')
      return false
    }
    if (!this.data.provinceCity || this.data.provinceCity == '') {
      this.showErrorMessage('地址省市县不能为空')
      return false
    }
    if(commentUtils.isEmoji(this.data.provinceCity)){
      this.showErrorMessage('地址省市县不能含有表情字符')
      return false
    }
    if (!data.detailAddress || data.detailAddress == '') {
      this.showErrorMessage('详细地址不能为空')
      return false
    }
    if(commentUtils.isEmoji(data.detailAddress)){
      this.showErrorMessage('详细地址不能含有表情字符')
      return false
    }

    // if (mainDriverLicense.length === 0) {
    //   this.showErrorMessage('驾驶证图片不能为空')
    //   return false
    // }
    // if (hasCar==='Y' && vehicleLicense.length === 0) {
    //   this.showErrorMessage('行驶证图片不能为空')
    //   return false
    // }
    // if(idCards.length<2){
    //   this.showErrorMessage('请上传身份证正反面')
    //   return false
    // }
    return true;
  },
  hidePlateNumber() {
    this.setData({
      ifPlateNumber: false,
    })
  },
  handleChangeAuthType(event) {
    this.setData({
      authType: event.currentTarget.dataset.authtype,
    });
  },
  handleChangeIndustry(event) {
    this.setData({
      industryId: event.currentTarget.dataset.industry,
    });
  },
  changePlateNumber(event) {
    const { detail } = event;
    wx.setStorageSync('plateNumber', detail);
    this.setData({
      plateNumber: detail,
    })
    this.hidePlateNumber();
  },
  showPlateNumber() {
    this.setData({
      ifPlateNumber: true,
    })
  },
  afterSFZRead(event){
    const { file } = event.detail;
    let uploadUrl = requestUrls.baseUrl + requestUrls.uploadUrl.idCard;
    let filePath = file.path;
    let imgList = this.data.idCards;
    this.setData({ showLoading: true });
    imageUtils.uploadImage(uploadUrl, filePath, (url) => {
      imgList.push({ url: requestUrls.baseImagePrefixUrl + url, imageUrl: url });
      this.setData({
        idCards: imgList,
      });
      this.setData({ showLoading: false });
    });
  },
  afterJSZRead(event) {
    const { file } = event.detail;
    let uploadUrl = requestUrls.baseUrl + requestUrls.uploadUrl.driverLisence;
    let filePath = file.path;
    let imgList = [];
    this.setData({ showLoading: true });
    imageUtils.uploadImage(uploadUrl, filePath, (url) => {
      imgList.push({ url: requestUrls.baseImagePrefixUrl + url, imageUrl: url });
      this.setData({
        mainDriverLicense: imgList,
      });
      wx.setStorageSync('mainDriverLicense', imgList);
      this.setData({ showLoading: false });
    });
  },
  afterXSZRead(event) {
    const { file } = event.detail;
    let uploadUrl = requestUrls.baseUrl + requestUrls.uploadUrl.drivingLisence;
    let filePath = file.path;
    let imgList = [];
    this.setData({ showLoading: true });
    imageUtils.uploadImage(uploadUrl, filePath, (url) => {
      imgList.push({ url: requestUrls.baseImagePrefixUrl + url, imageUrl: url })
      this.setData({
        vehicleLicense: imgList,
      });
      wx.setStorageSync('vehicleLicense', imgList);
      this.setData({ showLoading: false });
    });
  },
  removeJSZ() {
    this.setData({
      mainDriverLicense: [],
    })
  },
  removeXSZ() {
    this.setData({
      vehicleLicense: [],
    })
  },
  removeSFZ(event){
    console.log(event.detail.index);
    let imgList = this.data.idCards;
    imgList.splice(event.detail.index,1);
    this.setData({
      idCards:imgList,
    });
  },
  getDriverInfo() {
    if (!this.data.openid) {
      this.setData({
        openid: wx.getStorageSync('openid')
      })
    }
    let param = {
      'openid': this.data.openid
    }
    // requestUtil.postRequest(requestUrls.driver.getDriverInfo, param, (res) => {
    //     console.log(res)
    //     if (res.resCode === 9003) {
    //         this.setData({
    //             driverInfo: {
    //                 driverLience: [],
    //                 drivingLience: []
    //             }
    //         })
    //         return
    //     }
    //     let info = res.resData
    //     let driverLience = []
    //     info.driverLience ? driverLience.push(info.driverLience) : ''
    //     info.driverLience = driverLience
    //     let drivingLience = []
    //     info.drivingLience ? drivingLience.push(info.drivingLience) : ''
    //     info.drivingLience = drivingLience
    //     info.companyRegion = info.companyRegion ? info.companyRegion.split(',') : null
    //     this.setData({
    //         driverInfo: info
    //     })
    // }, () => {})
    // requestUtil.getRequest(requestUrls.driver.industryList, param, (res) => {
    //   console.log(res)
    //   if (res && res.length) {
    //     this.setData({
    //       industryList: res.map(item => ({
    //         id: item.id,
    //         name: item.name
    //       }))
    //     })
    //   }
    // }, () => { })
  },
  showErrorMessage(msg) {
    $Message({
      content: msg,
      type: 'error'
    })
  },
  checkTelPhone(){
    let telPhone = wx.getStorageSync('telPhone');
    console.log(telPhone);
    if(telPhone){
      this.setData({
        telPhone,
      })
    }
    if(!telPhone){
      setTimeout(() => {
        this.checkTelPhone();
      }, 100)
    }
  },
  getWxAddress(){
    wx.chooseAddress({
      success: (res)=>{
        this.setData({
          employeeName : res.userName,
          provinceCity:res.provinceName+res.cityName+res.countyName,
          detailAddress:res.detailInfo,
          provinceName:res.provinceName,
          cityName:res.cityName,
          countyName:res.countyName,
        });
      },
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.data.type = options.type || '1'
    //获取全局分销码
    // this.data.distributeCode = getApp().getDistributeCode()
    //获取司机初始化数据
    // this.getDriverInfo()
    this.checkTelPhone();
    this.setData({
      type:options.type || '1',
      distributeCode:getApp().getDistributeCode(),
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})